package com.ltmonitor.web.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import com.ltmonitor.entity.*;
import com.ltmonitor.service.IVehicleStateIconConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.service.IAlarmConfigService;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.MapFixService;
import com.ltmonitor.util.Constants;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.vo.PointLatLng;
import com.ltmonitor.web.util.JsonMessage;

/**
 * 实时数据查询
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/realData")
public class RealDataAction extends PaginateAction {
	private static String REGISTER_SIMNO_KEY = "registerSimNos";
	/**
	 * session 主键，存放此主键的map
	 */
	private static String UPDATE_KEY = "session_update_realdata";

	@Autowired
	private IRealDataService realDataService;

	/**
	 * 报警参数配置
	 */
	@Autowired
	protected IAlarmConfigService alarmConfigService;

	/**
	 * 用户选择要监控的车辆
	 * 
	 * @param registerVehicleIds
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/registerVehicles.action")
	public JsonMessage registerVehicles(String registerVehicleIds) {
		getVehicleIdList().clear();
		if (StringUtil.isNullOrEmpty(registerVehicleIds) == false) {
			String[] vehicleIds = registerVehicleIds.split(",");
			List simNoList = getSimNoListFromSession();
			simNoList.clear();

			List<Long> vehicleIdList = this.getVehicleIdList();
			for (String strVehicleId : vehicleIds) {
				// vehicleIdList.add(Integer.parseInt(vehicleId));
				long vehicleId = Long.parseLong(strVehicleId);
				vehicleIdList.add(vehicleId);

				VehicleData vd = this.vehicleDataService.load(vehicleId);
				simNoList.add(vd.getSimNo());
			}

			this.LogOperation("实时监控车辆，选择车辆数:" + vehicleIds.length);
		} else {
		}
		return json(true, "");
	}

	private List<Long> getVehicleIdList() {
		CopyOnWriteArrayList<Long> vehicleIdList = (CopyOnWriteArrayList<Long>) this
				.getFromSession(REGISTER_VEHICLEID_KEY);
		if (vehicleIdList == null) {
			vehicleIdList = new CopyOnWriteArrayList<Long>();
			this.putSession(REGISTER_VEHICLEID_KEY, vehicleIdList);
		}
		return vehicleIdList;
	}

	private List getSimNoListFromSession() {
		List<String> simNoList = (List<String>) this
				.getFromSession(REGISTER_SIMNO_KEY);
		if (simNoList == null) {
			simNoList = new ArrayList<String>();
			putSession(REGISTER_SIMNO_KEY, simNoList);
		}
		return simNoList;

	}

	private Map<Long, Date> getUpdateMap() {
		Map<Long, Date> updateMap = (Map<Long, Date>) getFromSession(UPDATE_KEY);
		if (updateMap == null) {
			updateMap = new HashMap<Long, Date>();
			putSession(UPDATE_KEY, updateMap);
		}
		return updateMap;
	}

	@RequestMapping("/view.action")
	public String viewRealData(long vehicleId, Model m) {
		Map params = new HashMap();
		params.put("vehicleId1", vehicleId);
		params.put("vehicleId", vehicleId);

		Map gpsData = new HashMap();
		try {
			String queryId = "vehicle.selectVehicleInfo"; // 查询单个车辆的综合信息
			List<Map<String, Object>> result = this.queryService.query(queryId,
					params);
			if (result.size() > 0) {
				gpsData = (Map) result.get(0);
				String simNo = "" + gpsData.get("simNo");
				if (realDataService != null) {
					GPSRealData rd = realDataService.get(simNo);
					if (rd != null) {
						// 将实时数据更新到map
						VehicleData vd = this.vehicleDataService.load(rd.getVehicleId());
						setRealDataMap(gpsData, rd,vd);

						gpsData.put("vehicleId", vd.getEntityId());
					}
				}
				this.convert2(gpsData);

			}
		} catch (Exception ex) {
			m.addAttribute("message", ex.getMessage());
			log.error(ex.getMessage(), ex);
		}
		m.addAttribute("gpsData", gpsData);
		m.addAttribute("hasRealTimeVideoAuthority", hasRealTimeVideoAuthority());
		return "realData/viewRealData";
	}

	/**
	 * 刷新视频的OSD字幕叠加信息
	 * @param update
	 * @param simNoList
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/refreshOsdData.action")
	public JsonMessage refreshOsdData(boolean update,String[] simNoList)
	{
		try {
			List<GPSRealData> result = new ArrayList<GPSRealData>();
			for (String simNo : simNoList) {
				GPSRealData rd = this.realDataService.get(simNo);
				result.add(rd);
			}
			return json(true, result);
		}catch (Exception ex)
		{
			log.error(ex.getMessage(),ex);
			return json(false,ex.getMessage());
		}
	}

	/**
	 * 刷新实时数据，前端不断的采用定时刷新的方式获取实时数据，刷新实时数据表格。 如果和以前的数据没有变化，则直接不刷新，只刷新GPS数据发生变化的数据
	 * 
	 * @param update
	 *            第一次整个加载，第二次是判断更新，如果GPS状态发生了变化，才更新到前端
	 * @param vehicleId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/refresh.action")
	public JsonMessage refreshRealData(boolean update,
			@RequestParam(defaultValue = "0") long vehicleId) {

		// String queryId = "selectGpsRealData";

		Map params = new HashMap();
		// params.put("userId", getUserId());
		if (vehicleId > 0) {
			// 单车监控，用于生成监控车辆轨迹
			params.put("vehicleId1", vehicleId);
			params.put("vehicleId", vehicleId);
			try {
				String queryId = "vehicle.selectVehicleInfo"; // 查询单个车辆的综合信息
				List<Map<String, Object>> result = this.queryService.query(
						queryId, params);
				VehicleData vd = this.vehicleDataService.load(vehicleId);
				if (result.size() > 0) {
					Map resultMap = (Map) result.get(0);
					String simNo = "" + resultMap.get("simNo");
					if (realDataService != null) {
						GPSRealData rd = realDataService.get(simNo);
						if (rd != null) {
							// 将实时数据更新到map
							setRealDataMap(resultMap, rd,vd);
							String mapIcon = this.getMapIcon(vd, rd);
							resultMap.put("vehicleIcon", mapIcon);
						}
					}
					this.convert(resultMap);
					return json(true, resultMap);
				} else
					return json(false, "没有查询到该车辆的实时数据");
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
				return json(false, ex.getMessage());
			}
		} else {
			List ls = new ArrayList();
			if (getVehicleIdList().isEmpty() == false) {
				// Date start = new Date();
				try {
					ls = this.getRealDataList(update);
					// Date start2 = new Date();
					// List ls = convert(result);
					// dataOutPut.put("rows", ls);
				} catch (Exception ex) {
					log.error(ex.getMessage(), ex);
				}

				// Date end = new Date();
				// double seconds = DateUtil.getSeconds(start, end);
				// log.error("查询数据耗时:" + seconds);
			}
			return json(true, ls);
		}
	}

	private List<Map> getRealDataList(boolean update) {

		// Date end1 = new Date();
		// double seconds1 = DateUtil.getSeconds(start1, end1);
		// log.error("车辆查询耗时:" + seconds1 );
		// 开始调用808服务器的实时数据服务，获取实时数据
		Map<Long, GPSRealData> realDataMap = new HashMap<Long, GPSRealData>();
		ArrayList filterResult = new ArrayList();
		Map<Long, Date> updateMap = this.getUpdateMap();
		if (update == false) {
			updateMap.clear();// 第一次加载要清空表格
		}

		List<Long> vehicleIdList = this.getVehicleIdList();
		for (long vehicleId : vehicleIdList) {
			VehicleData vd = this.vehicleDataService.load(vehicleId);
			Map<String, Comparable> rowData = new HashMap();
			Department dep = this.departmentService.fetchDepartment(vd
					.getDepId());
			rowData.put("vehicleId", vd.getEntityId());
			rowData.put("depId", vd.getDepId());
			rowData.put("depName", dep.getName());
			rowData.put("plateColor", vd.getPlateColor());
			rowData.put("simNo", vd.getSimNo());
			rowData.put("plateNo", vd.getPlateNo());

			GPSRealData rd = this.realDataService.get(vd.getSimNo());
			Date sendTime = null;
			if (rd != null) {
				setRealDataMap(rowData, rd,vd);
				sendTime = rd.getSendTime();
			}
			if (update) {
				Date lastSendTime = updateMap.get(vehicleId);
				if (rd != null && rd.getOnline() == false) {
					if (lastSendTime != null) {
						sendTime = null;
					} else
						continue;
				} else if (sendTime == null
						|| (lastSendTime != null && sendTime
								.compareTo(lastSendTime) == 0)) {
					continue;// 说明数据没有发生变化,不刷新
				}
			}
			rowData.put("vehicleIcon", this.getMapIcon(vd, rd));
			updateMap.put(vehicleId, sendTime);
			try {
				// 对返回的每行数据，进行格式化转换
				convert(rowData);
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
			}
			filterResult.add(rowData);
		}

		return filterResult;
	}

	private static DecimalFormat coordinateFormat = new DecimalFormat("#.000000");
	private static DecimalFormat velocityFormat = new DecimalFormat("#.0");
	private void setRealDataMap(Map rowData, GPSRealData rd, VehicleData vd) {
		rowData.put("ID", rd.getID());
		rowData.put("valid", rd.IsValid());
		rowData.put("latitude", coordinateFormat.format(rd.getLatitude()));
		rowData.put("longitude", coordinateFormat.format(rd.getLongitude()));
		rowData.put("altitude", rd.getAltitude());
		rowData.put("alarmState", rd.getAlarmState());
		rowData.put("status", rd.getStatus());
		rowData.put("gas", (int)rd.getGas());
		rowData.put("signal", rd.getSignalState());
		rowData.put("location", rd.getLocation());
		rowData.put("mileage", (int)rd.getMileage());
		rowData.put("updateDate", rd.getUpdateDate());
		if(rd.getLastDayMileage() >= 0)
		{
			double m = rd.getMileage() - rd.getLastDayMileage();
			DecimalFormat df = new DecimalFormat("#.0"); 
			rowData.put("todayMileage", df.format(m));
		}else
		{
			rowData.put("todayMileage", rd.getMileage() / 1.0);			
		}
		rowData.put("online", rd.getOnline());
		rowData.put("sendTime", rd.getSendTime());
		rowData.put("velocity", velocityFormat.format(rd.getVelocity()));
		if (rd.getVelocity() == 0 && rd.getParkingTime() != null) {
			// 计算出停车的时间，以分钟为单位
			double parkingTime = 0.1 * DateUtil.getSeconds(rd.getParkingTime(),
					new Date()) / 6;
			String strVelocity = "停车（"
					+ Constants.getIntervalDescr(parkingTime) + ")";
			rowData.put("velocityDescr", strVelocity);
		} else {
			rowData.put("velocityDescr", rd.getVelocity());
		}

		rowData.put("recordVelocity", velocityFormat.format(rd.getRecordVelocity()));
		rowData.put("direction", rd.getDirection());
		rowData.put("areaAlarm", rd.getAreaAlarm());
		rowData.put("areaType", rd.getAreaType());
		rowData.put("areaId", rd.getAreaId());
		rowData.put("overSpeedAreaId", rd.getOverSpeedAreaId());
		rowData.put("overSpeedAreaType", rd.getOverSpeedAreaType());
		rowData.put("routeAlarmType", rd.getRouteAlarmType());
		rowData.put("routeSegmentId", rd.getRouteSegmentId());
		rowData.put("runTimeOnRoute", rd.getRunTimeOnRoute());

		String videoAlarmDescr = this.getVideoAlarmDescr(rd,vd);
		if(StringUtil.isNullOrEmpty(videoAlarmDescr) == false)
		{
			rowData.put("videoAlarmDescr", videoAlarmDescr);
		}
		//平台报警
		StringBuilder platformAlarmDescr = new StringBuilder();
		if(StringUtil.isNullOrEmpty(rd.getMapAreaAlarm()) == false)
		{
			platformAlarmDescr.append("区域报警:" + rd.getMapAreaAlarm());
		}
		if(StringUtil.isNullOrEmpty(rd.getOffsetRouteAlarm()) == false)
		{
			platformAlarmDescr.append("线路偏移报警:" + rd.getOffsetRouteAlarm());
		}
		if(StringUtil.isNullOrEmpty(rd.getOverSpeedAlarm()) == false)
		{
			platformAlarmDescr.append("分段限速报警:" + rd.getOverSpeedAlarm());
		}
		if(StringUtil.isNullOrEmpty(rd.getArriveKeyPlaceAlarm()) == false)
		{
			platformAlarmDescr.append("未按规定时间到达关键点报警:" + rd.getArriveKeyPlaceAlarm());
		}
		if(StringUtil.isNullOrEmpty(rd.getArriveKeyPlaceAlarm()) == false)
		{
			platformAlarmDescr.append("未按规定时间离开关键点报警:" + rd.getLeaveKeyPlaceAlarm());
		}
		rowData.put("platformAlarmDescr", platformAlarmDescr.toString());
	}

	private String getVideoAlarmDescr(GPSRealData rd,VehicleData vd)
	{
		int alarm = rd.getVideoAlarm();
		StringBuilder sb = new StringBuilder();
		for(int m = 0; m < 32; m++)
		{
			String alarmType = ""+ (32 + m);
			if(StringUtil.valueAtBit(alarm, m))
			{
				AlarmConfig c = this.alarmConfigService.getAlarmConfig(0, alarmType, AlarmRecord.ALARM_FROM_VIDEO);
				if(c != null && c.isEnabled()) {
					sb.append(c.getName()).append(",");

					if(m == 0)
					{
						sb.append("丢失通道:");
						//视频信号丢失报警
						int channelNum = vd.getVideoChannelNum();
						int videoLossAlarm = rd.getVideoLossAlarmStatus();
						for(int ch = 0; ch < channelNum; ch++)
						{
							if(StringUtil.valueAtBit(videoLossAlarm,ch))
								sb.append(ch+1).append(",");
						}
					}else if(m == 1)
					{
						sb.append("遮挡通道:");
						//视频信号丢失报警
						int channelNum = vd.getVideoChannelNum();
						int videoCoverAlarm = rd.getVideoCoverAlarmStatus();
						for(int ch = 0; ch < channelNum; ch++)
						{
							if(StringUtil.valueAtBit(videoCoverAlarm,ch))
								sb.append(ch+1).append(",");
						}
					}else if(m == 2)
					{
						int diskFualtAlarm = rd.getVideoStorageFaultAlarmStatus();

						if(diskFualtAlarm != 0)
						{
							String strDisk = vd.getVideoDisk();
							if(StringUtil.isNullOrEmpty(strDisk) == false)
							{
								String[] disks = strDisk.split(",");
								for(String d : disks)
								{
									int index = Integer.parseInt(d);
									if(StringUtil.valueAtBit(diskFualtAlarm,index))
									{
										index += 1;
										if(index < 13)
											sb.append(index + "号主存储器").append(",");
										else
										{
											index = index - 12;
											sb.append(index + "号灾备器").append(",");
										}
									}
								}
							}
						}
					}
					else if( m == 5)
					{
						//异常驾驶行为报警
						int driverALarm = rd.getUnusualDriveBeaviour();
						for(int k = 0; k < 16;k++)
						{
							if(StringUtil.valueAtBit(driverALarm,k))
							{
								sb.append(getUnusualDriveBehaviourDescr(k));
							}
						}
						sb.append(",疲劳程度:" + rd.getTiredLevel());
					}
				}
			}
		}


		return sb.toString();
	}

	private String getUnusualDriveBehaviourDescr(int type)
	{
		if(type == 0)
			return "疲劳";
		else if(type == 1)
		    return "打电话";
		else if(type == 2)
			return "抽烟";
		else
			return "未定义";
	}

	
	/**
	 * 结果转换，对状态、车牌颜色等整数字段转成用户可以阅读的文字描述。
	 * 
	 * @param ls
	 * @param update 是否是更新模式， 第一次加载的时候是全部加载，以后就转为更新模式，只加载变化的数据
	 */
	private List convert(List ls, boolean update) {
		ArrayList filterResult = new ArrayList();
		Map<Long, Date> updateMap = this.getUpdateMap();
		if (update == false) {
			updateMap.clear();// 第一次加载要清空表格
		}
		for (Object rowData : ls) {
			Map rd = (Map) rowData;
			long vehicleId = (Long) rd.get("vehicleId");
			Date sendTime = (Date) rd.get("sendTime");
			if (update && updateMap.containsKey(vehicleId)) {
				Date lastSendTime = updateMap.get(vehicleId);
				if (sendTime == null
						|| (lastSendTime != null && sendTime
								.compareTo(lastSendTime) == 0)) {
					continue;// 说明数据没有发生变化,不刷新
				}
			}
			updateMap.put(vehicleId, sendTime);
			try {
				// 对返回的每行数据，进行格式化转换
				convert(rd);
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
			}
			filterResult.add(rd);

		}
		return filterResult;
	}

	private void convert(Map rowData) {
		// 根据系统配置的显示类型，显示状态
		String displaySignalState = this.getSystemConfig()
				.getDisplayStateType();
		if (Constants.STATE_TYPE_BARKER.equals(displaySignalState)) {
			// 显示刹车、转向
			int signal = rowData.get("signal") != null ? (Integer) rowData
					.get("signal") : 0;
			// signal = 24;
			String descr = this.getSignalDescr(signal);
			rowData.put("status", descr);
		} else {
			// 显示车辆ACC开关等状态
			String status = "" + rowData.get("status");
			String descr = getStatusDescr(status);
			rowData.put("status", descr);
		}

		String alarmState = "" + rowData.get("alarmState");

		long depId = 0;
		if (rowData.containsKey("depId")) {
			depId = Long.parseLong(""+rowData.get("depId"));
		}
		alarmState = this.getAlarmDescr(depId, alarmState);

		if (rowData.get("valid") != null) {
			boolean valid = (Boolean) rowData.get("valid");
			rowData.put("valid", valid ? "有效" : "无效");
		}

		// String vehicleType = "" + rowData.get("vehicleType");
		this.convert(rowData, "vehicleType", "VehicleType");

		if (rowData.get("driverName") == null) {
			rowData.put("driverName", "");
		}

		if (rowData.get("ewayBill") == null) {
			rowData.put("ewayBill", "");
		}

		// String plateColor = "" + rowData.get("plateColor");
		this.convert(rowData, "plateColor", "plateColor");
		Date sendTime = (Date) rowData.get("sendTime");
		if (sendTime != null) {
			rowData.put("sendTime",
					DateUtil.toStringByFormat(sendTime, "MM-dd HH:mm:ss"));

			Double latitude = Double.parseDouble("" + rowData.get("latitude"));
			Double longitude = Double
					.parseDouble("" + rowData.get("longitude"));
			// 坐标加偏
			PointLatLng pl = MapFixService.fix(latitude, longitude,
					super.getMapType());
			rowData.put("latitude", pl.getLat());
			rowData.put("longitude", pl.getLng());

			rowData.put("orgLatitude", latitude);
			rowData.put("orgLongitude", longitude);

			int direction = (Integer) rowData.get("direction");
			String directionDescr = this.getDirectionDescr(direction);
			rowData.put("directionDescr", directionDescr);

			int areaType = (Integer) rowData.get("areaType");
			if (areaType > 0 && rowData.get("areaId") != null) {
				long areaId = Long.parseLong("" + rowData.get("areaId"));
				int areaAlarm = (Integer) rowData.get("areaAlarm");
				String temp = areaAlarm == 0 ? "进入" : "离开";
				alarmState += this.getAreaTypeDescr(areaType) + "Id:" + areaId
						+ temp + "报警,";
			}

			int overSpeedAreaType = (Integer) rowData.get("overSpeedAreaType");
			int overSpeedAreaId = (Integer) rowData.get("overSpeedAreaId");
			if (overSpeedAreaType > 0) {
				alarmState += this.getAreaTypeDescr(overSpeedAreaType) + "Id:"
						+ overSpeedAreaId + "超速报警,";
			}
			int routeSegmentId = (Integer) rowData.get("routeSegmentId");
			int routeAlarmType = (Integer) rowData.get("routeAlarmType");
			if (routeSegmentId > 0) {
				long areaId = Long.parseLong("" + rowData.get("areaId"));
				int runTimeOnRoute = (Integer) rowData.get("runTimeOnRoute");
				String temp = routeAlarmType == 0 ? "不足" : "过长";
				alarmState += "路段Id:" + areaId + "行驶时间:" + runTimeOnRoute
						+ "秒,行驶" + temp + "报警,";
			}

			String videoAlarmDescr = (String)rowData.get("videoAlarmDescr");
			if(StringUtil.isNullOrEmpty(videoAlarmDescr) == false)
			{
				alarmState += " " + videoAlarmDescr;
			}


			String platformAlarmDescr = (String)rowData.get("platformAlarmDescr");
			if(StringUtil.isNullOrEmpty(platformAlarmDescr) == false)
			{
				alarmState += " " + platformAlarmDescr;
			}

		}
		if (rowData.get("location") == null) {
			rowData.put("location", "");
		}

		if (StringUtil.isNullOrEmpty(alarmState))
			alarmState = "无";
		rowData.put("alarmStateDescr", alarmState);// 报警状态描述

	}
	
	private void convert2(Map rowData) {
		// 根据系统配置的显示类型，显示状态
		String displaySignalState = this.getSystemConfig()
				.getDisplayStateType();
		if (Constants.STATE_TYPE_BARKER.equals(displaySignalState)) {
			// 显示刹车、转向
			int signal = rowData.get("signal") != null ? (Integer) rowData
					.get("signal") : 0;
			// signal = 24;
			String descr = this.getSignalDescr(signal);
			rowData.put("status", descr);
		} else {
			// 显示车辆ACC开关等状态
			String status = "" + rowData.get("status");
			String descr = getStatusDescr(status);
			rowData.put("status", descr);
		}

		String alarmState = "" + rowData.get("alarmState");

		long depId = 0;
		if (rowData.containsKey("depId")) {
			depId = Long.parseLong(""+rowData.get("depId"));
		}
		alarmState = this.getAlarmDescr2(depId, alarmState);

		if (rowData.get("valid") != null) {
			boolean valid = (Boolean) rowData.get("valid");
			rowData.put("valid", valid ? "有效" : "无效");
		}

		// String vehicleType = "" + rowData.get("vehicleType");
		this.convert(rowData, "vehicleType", "VehicleType");

		if (rowData.get("driverName") == null) {
			rowData.put("driverName", "");
		}

		if (rowData.get("ewayBill") == null) {
			rowData.put("ewayBill", "");
		}

		// String plateColor = "" + rowData.get("plateColor");
		this.convert(rowData, "plateColor", "plateColor");
		Date sendTime = (Date) rowData.get("sendTime");
		if (sendTime != null) {
			rowData.put("sendTime",
					DateUtil.toStringByFormat(sendTime, "MM-dd HH:mm:ss"));

			Double latitude = Double.parseDouble("" + rowData.get("latitude"));
			Double longitude = Double
					.parseDouble("" + rowData.get("longitude"));
			// 坐标加偏
			PointLatLng pl = MapFixService.fix(latitude, longitude,
					super.getMapType());
			rowData.put("latitude", pl.getLat());
			rowData.put("longitude", pl.getLng());

			rowData.put("orgLatitude", latitude);
			rowData.put("orgLongitude", longitude);

			int direction = (Integer) rowData.get("direction");
			String directionDescr = this.getDirectionDescr(direction);
			rowData.put("directionDescr", directionDescr);

			/*
			int areaType = (Integer) rowData.get("areaType");
			if (areaType > 0 && rowData.get("areaId") != null) {
				long areaId = Long.parseLong("" + rowData.get("areaId"));
				int areaAlarm = (Integer) rowData.get("areaAlarm");
				String temp = areaAlarm == 0 ? "进入" : "离开";
				alarmState += this.getAreaTypeDescr(areaType) + "Id:" + areaId
						+ temp + "报警,";
			}

			int overSpeedAreaType = (Integer) rowData.get("overSpeedAreaType");
			int overSpeedAreaId = (Integer) rowData.get("overSpeedAreaId");
			if (overSpeedAreaType > 0) {
				alarmState += this.getAreaTypeDescr(overSpeedAreaType) + "Id:"
						+ overSpeedAreaId + "超速报警,";
			}
			int routeSegmentId = (Integer) rowData.get("routeSegmentId");
			int routeAlarmType = (Integer) rowData.get("routeAlarmType");
			if (routeSegmentId > 0) {
				long areaId = Long.parseLong("" + rowData.get("areaId"));
				int runTimeOnRoute = (Integer) rowData.get("runTimeOnRoute");
				String temp = routeAlarmType == 0 ? "不足" : "过长";
				alarmState += "路段Id:" + areaId + "行驶时间:" + runTimeOnRoute
						+ "秒,行驶" + temp + "报警,";
			}

			String videoAlarmDescr = (String)rowData.get("videoAlarmDescr");
			if(StringUtil.isNullOrEmpty(videoAlarmDescr) == false)
			{
				alarmState += " " + videoAlarmDescr;
			}


			String platformAlarmDescr = (String)rowData.get("platformAlarmDescr");
			if(StringUtil.isNullOrEmpty(platformAlarmDescr) == false)
			{
				alarmState += " " + platformAlarmDescr;
			}*/

		}
		if (rowData.get("location") == null) {
			rowData.put("location", "");
		}

		if (StringUtil.isNullOrEmpty(alarmState))
			alarmState = "无";
		rowData.put("alarmStateDescr", alarmState);// 报警状态描述

	}

	/**
	 * 0：无特定位置； 1：圆形区域； 2：矩形区域； 3：多边形区域； 4：路段
	 * 
	 * @param areaType
	 * @return
	 */
	protected String getAreaTypeDescr(int areaType) {
		if (areaType == 0)
			return "无特定位置";
		else if (areaType == 1)
			return "圆形区域";
		else if (areaType == 2)
			return "矩形区域";
		else if (areaType == 3)
			return "多边形区域";
		else if (areaType == 4)
			return "路段";
		return "未知区域类型";
	}

	protected String getDirectionDescr(int direction) {
		String descr = "";
		if (direction == 0) {
			descr = "正北";
		} else if (direction == 90) {
			descr = "正东";
		} else if (direction == 180) {
			descr = "正南";
		} else if (direction == 270) {
			descr = "正西";
		} else if (direction == 45) {
			descr = "东北";
		} else if (direction == 135) {
			descr = "东南";
		} else if (direction == 225) {
			descr = "西南";
		} else if (direction == 315) {
			descr = "西北";
		} else if (direction < 90) {
			descr = "东偏北" + direction + "度";
		} else if (direction > 90 && direction < 180) {
			descr = "东偏南" + (direction - 90) + "度";
		} else if (direction > 180 && direction < 270) {
			descr = "西偏南" + (270 - direction) + "度";
		} else if (direction > 270 && direction < 360) {
			descr = "西偏北" + (direction - 270) + "度";
		}
		return descr;
	}

	protected String getStatusDescr(String status) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isNullOrEmpty(status) == false) {
			char[] ch = status.toCharArray();
			if (ch.length == 32) {
				int m = 31;
				int c = ch[m - 0] - 48;
				sb.append(c == 1 ? "ACC开" : "ACC关").append(",");
				c = ch[m - 1] - 48;
				sb.append(c == 1 ? "定位" : "未定位").append(",");
				c = ch[m - 2] - 48;
				sb.append(c == 1 ? "南纬" : "北纬").append(",");
				c = ch[m - 3] - 48;
				sb.append(c == 1 ? "西经" : "东经").append(",");
				c = ch[m - 4] - 48;
				sb.append(c == 1 ? "停运" : "运营").append(",");
				c = ch[m - 10] - 48;
				sb.append(c == 1 ? "油路断开" : "油路正常").append(",");
				c = ch[m - 11] - 48;
				sb.append(c == 1 ? "电路断开" : "电路正常").append(",");
				c = ch[m - 12] - 48;
				sb.append(c == 1 ? "车门加锁" : "车门解锁").append(",");
			}
		}

		return sb.toString();
	}

	private static String[] signalDescr = new String[] { "近光灯", "远光灯", "右转向灯",
			"左转向灯", "制动", "倒档" };

	protected String getSignalDescr(int signal) {
		StringBuilder sb = new StringBuilder();
		String strStatus = Integer.toBinaryString(signal);
		strStatus = StringUtil.leftPad(strStatus, 32, '0');

		char[] ch = strStatus.toCharArray();
		for (int m = 0; m < ch.length && m < signalDescr.length; m++) {
			int c = ch[31 - m] - 48;
			if (StringUtil.isNullOrEmpty(signalDescr[m]) == false) {
				sb.append(signalDescr[m]).append(c == 1 ? "开" : "关")
						.append(",");
			}
		}

		return sb.toString();
	}

	/**
	 * 报警描述
	 * 
	 * @param alarm
	 * @return
	 */
	protected String getAlarmDescr(long depId, String alarm) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isNullOrEmpty(alarm) == false) {
			char[] ch = alarm.toCharArray();
			for (int m = 0; m < ch.length; m++) {
				int tag = Integer.parseInt("" + ch[m]);
				int alarmId = 31 - m; // 倒序，转换为部标的报警序号
//				if (tag == 1
//						&& alarmConfigService.isAlarmEnabled(depId, ""
//								+ alarmId, AlarmRecord.ALARM_FROM_TERM)) {
				if (tag == 1){
					BasicData bd = basicDataService.getBasicDataByCode(""
							+ alarmId, "AlarmType");
					if (bd != null) {
						sb.append(bd.getName()).append(",");
					}
				}
			}
		}



		return sb.toString();
	}
	
	/**
	 * 报警描述
	 * 
	 * @param alarm
	 * @return
	 */
	protected String getAlarmDescr2(long depId, String alarm) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isNullOrEmpty(alarm) == false) {
			char[] ch = alarm.toCharArray();
			for (int m = 0; m < ch.length; m++) {
				int tag = Integer.parseInt("" + ch[m]);
				int alarmId = 31 - m; // 倒序，转换为部标的报警序号
				if (tag == 1) {
					BasicData bd = basicDataService.getBasicDataByCode(""
							+ alarmId, "AlarmType");
					if (bd != null) {
						sb.append(bd.getName()).append(",");
					}
				}
			}
		}



		return sb.toString();
	}


}
